from django.shortcuts import render, redirect
from ManageApp.models import Department


def depart_list(req):
    queryset = Department.objects.all()
    content = {
        "queryset": queryset,
    }
    return render(req,'depart_list.html', content)


def depart_edit(req, nid):
    # 传nid的好处是可以跳到新页面，需要写新url
    obj_row = Department.objects.filter(department_id=nid)
    if req.method == "GET":
        content = {
            "department_id": obj_row.first().department_id,
            "title": obj_row.first().title,
        }
        return render(req, 'depart_edit.html', content)
    else:
        new_title = req.POST.get('new_title')
        obj_row.update(title=new_title)
        return redirect('/depart/list')


def depart_delete(req):
    # 不传nid 不用再写新页面和url
    nid = req.GET.get('nid')
    obj_row = Department.objects.filter(department_id=nid)
    if not obj_row:
        return render(req, 'error.html')
    obj_row.delete()
    return redirect('/depart/list')


def depart_add(req):
    if req.method == "GET":
        return render(req, 'depart_add.html')
    else:
        new_title = req.POST.get('new_title')
        Department.objects.create(title=new_title)
        return redirect('/depart/list')


